<template>
  <div class="app-container">
    <!-- 标题栏 -->
    <div class="header-bar">
      <el-button type="primary" class="mb-4" @click="handleAdd">新建需求</el-button>
      <el-button class="mb-4 ml-2" @click="handleDownloadTemplate" style="margin-right: auto"
        >下载模板</el-button
      >
      <el-input
        placeholder="请输入需求编号/名称"
        style="width: 240px; float: right; margin-bottom: 20px"
        v-model="query.keyword"
        @keyup.enter="handleSearch"
        clearable
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>

    <!-- 数据表格 -->
    <el-table :data="requirementList" style="width: 100%" border>
      <el-table-column
        prop="dno"
        label="需求编号"
        align="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="dname"
        label="需求名称"
        align="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="dtype"
        label="需求类别"
        align="left">
        <template #default="scope">
          <span>{{ getRequirementTypeLabel(scope.row.dtype) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="materialName"
        label="物料内容"
        align="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="contractNo"
        label="关联合同号"
        align="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column prop="createBy" label="创建人" align="left" :show-overflow-tooltip="true" />
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="left"
        :show-overflow-tooltip="true"
      >
        <template #header>
          <div class="header-with-filter">
            <span>创建时间</span>
            <el-popover
              placement="bottom"
              width="300"
              trigger="click"
            >
              <template #reference>
                <el-button text size="small" class="calendar-button">
                  <el-icon class="search-icon"><Calendar /></el-icon>
                </el-button>
              </template>
              <div class="filter-content">
                <el-date-picker
                  v-model="query.timeInterval"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleSearch"
                  clearable
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="250" fixed="right">
        <template #default="scope" style="display: flex; align-items: center;">
          <!-- 当contractNo存在时显示查看按钮 -->
          <template v-if="scope.row.contractNo">
            <el-link type="primary" @click="handleView(scope.row)">查看</el-link>
          </template>
          <!-- 当contractNo不存在或为空时显示编辑、关联合同和删除按钮 -->
          <template v-else>
            <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link>
            <el-link type="primary" class="ml5" @click="handleLinkContract(scope.row)">关联合同</el-link>
            <el-link type="danger" class="ml5" @click="handleDelete(scope.row)">删除</el-link>
          </template>
          <!-- 无论contractNo是否存在，都显示下载按钮 -->
          <el-link type="primary" class="ml5" @click="handleDownload(scope.row)">下载</el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px; justify-content: flex-end"
      v-model:current-page="query.pageNum"
      v-model:page-size="query.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 使用新建的弹窗组件 -->
    <create-modal
      v-model:visible="dialogVisible"
      :requirement-type-options="requirementTypeOptions"
      :material-tree-data="materialTreeData"
      :edit-mode="editMode"
      @submit="handleModalSubmit"
    />

    <!-- 关联合同弹窗组件 -->
    <relate-contract
      v-model:visible="relateContractVisible"
      :requirement-type="selectedRequirementType"
      :requirement-data="selectedRequirementData"
      @submit="handleRelateContractSubmit"
    />

    <!-- 下载物料内容弹窗组件 -->
    <down-material-content
      v-model:visible="downloadMaterialVisible"
      :material-tree-data="materialTreeData"
      @download="handleMaterialDownload"
      @close="handleCloseDownloadMaterial"
    />
  </div>
</template>

<script setup name="RequirementManagement">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Filter } from '@element-plus/icons-vue'
// 导入新建的弹窗组件
import CreateModal from './createModal.vue'
// 导入关联合同弹窗组件
import RelateContract from './relateContract.vue'
// 导入下载物料内容弹窗组件
import DownMaterialContent from './downMaterialContent.vue'
import { useRouter } from 'vue-router'
import {
  getDemandPage,
  getDemandRandomCode,
  createDemand,
  removeDemand,
  relevanceContract
} from '@/api/business/demand'
import {
  getClassificationTree,
  getMaterialPage,
} from '@/api/system/materials'

const router = useRouter()
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  timeInterval: []
})
const total = ref(7) // 原始数据总数
const loading = ref(false)
// 需求类型选项
const requirementTypeOptions = ref([
  { label: '工程类', value: 1 },
  { label: '直销类', value: 2 }
])
const demandCode = ref('')
// const commonTitle = ref('新建需求')
const editMode = ref(false)
// 表格数据
const requirementList = ref([])
// 弹窗相关
const dialogVisible = ref(false)
// 关联合同弹窗相关
const relateContractVisible = ref(false)
const selectedRequirementData = ref({})
const selectedRequirementType = ref(0)

// 下载物料内容弹窗相关
const downloadMaterialVisible = ref(false)
// 物料树数据（模拟数据）
const materialTreeData = ref([])

// 保存原始分类数据
let classificationTreeData = []

// 物料内容
const fetchCategories = () => {
  getClassificationTree().then((res) => {
    if (res.data && Array.isArray(res.data)) {
      // 保存原始分类数据
      classificationTreeData = res.data
      // 初始化物料树数据结构
      updateMaterialTreeData([])
    } else {
      materialTreeData.value = []
      classificationTreeData = []
    }
  })
}

// 根据分类数据和物料数据更新物料树
const updateMaterialTreeData = (materials) => {
  if (!Array.isArray(classificationTreeData)) {
    materialTreeData.value = []
    return
  }
  
  // 转换数据格式，构造三级物料树
  materialTreeData.value = classificationTreeData.map(item => {
    // 一级分类节点
    const firstLevel = {
      label: item.name,
      value: item.id,
      disabled: true, // 一级分类不可选择
      children: []
    }
    
    // 处理二级分类节点
    if (item.children && item.children.length > 0) {
      firstLevel.children = item.children.map(child => {
        // 二级分类节点
        const secondLevel = {
          label: child.name,
          value: child.id,
          disabled: true, // 二级分类不可选择
          children: []
        }
        
        // 查找匹配当前二级分类的物料数据
        const matchedMaterials = materials.filter(material => 
          material.classification === child.id
        )
        
        // 添加三级物料节点
        if (matchedMaterials.length > 0) {
          secondLevel.children = matchedMaterials.map(material => ({
            label: material.materialName,
            value: material.id,
            disabled: false // 三级物料可选择
          }))
        }
        
        return secondLevel
      })
    }
    
    // 查找直接匹配一级分类的物料数据（如果有）
    const firstLevelMaterials = materials.filter(material => 
      material.classification === item.id
    )
    
    // 如果有直接匹配一级分类的物料，添加到每个二级分类下
    if (firstLevelMaterials.length > 0) {
      firstLevel.children.forEach(secondLevel => {
        firstLevelMaterials.forEach(material => {
          secondLevel.children.push({
            label: material.materialName,
            value: material.id,
            disabled: false
          })
        })
      })
    }
    
    return firstLevel
  })
}

// 查询物料分类下具体内容
const fetchMaterialDetails = () => {
  getMaterialPage({ pageNum: 1, pageSize: 10000,}).then(res => {
    if (res.code === 200 && res.data && res.data.list) {
      // 更新物料树数据
      updateMaterialTreeData(res.data.list)
    }
  })
}
// 获取需求唯一编号
const getDemandCode = async () => {
  getDemandRandomCode().then(res => {
    if (res.code === 200) {
      demandCode.value = res.data || ''
    }
  })
}

// 获取需求列表
const getRequirementList = async () => {
  loading.value = true
  
  getDemandPage(query).then(res => { 
    if (res.code === 200) {
      loading.value = false
      requirementList.value = res.data?.list || []
      total.value = res.data?.total || 0
    }
  }).catch(() => {
    loading.value = false
  })
}

// 初始化
onMounted(() => {
  // 初始化时不需要请求接口，直接使用假数据
  getRequirementList()
  // 初始化物料内容
  fetchCategories()
  fetchMaterialDetails()
  // 获取需求唯一编号
  getDemandCode()
})

// 处理模态框提交
const handleModalSubmit = (formData) => {
  const newFormData = { ...formData, maId: Number(formData.maId), deNo: demandCode.value }
  createDemand(newFormData).then(res => {
    if (res.code === 200) {
      ElMessage.success('新建成功')
      dialogVisible.value = false
      getRequirementList()
      getDemandCode()
      router.push({
        // path: `/business/contract/Requirement/createRequirement/${row.id}`
        path: `/business/contract/Requirement/createRequirement/`
      })
    }
  })
}

// 获取需求类型标签
function getRequirementTypeLabel(value) {
  const option = requirementTypeOptions.value.find((item) => item.value === value)
  return option ? option.label : value
}

// 搜索
function handleSearch() {
  query.pageNum = 1
  getRequirementList()
}

// 处理需求类型筛选
function handleTypeFilter() {
  // 重置页码
  query.pageNum = 1
  // 重新获取数据
  getRequirementList()
}

// 新建需求 - 打开弹窗
function handleAdd() {
  // commonTitle.value = '新建需求'
  editMode.value = false
  dialogVisible.value = true
}

// 下载模板
function handleDownloadTemplate() {
  downloadMaterialVisible.value = true
}

// 查看需求
function handleView(row) {
  router.push({
    path: `/business/contract/Requirement/requireDetails/${row.id}`
  })
}

// 处理编辑按钮点击事件
function handleEdit(row) {
  editMode.value = true
  router.push({
    path: `/business/contract/Requirement/createRequirement/${row.id}`
  })
}

// 下载需求
function handleDownload(row) {
  ElMessage.success(`下载需求：${row.dname}`)
}

// 处理下载物料内容
function handleMaterialDownload(selectedMaterials) {
  console.log('下载的物料:', selectedMaterials)
  ElMessage.success(`已选择${selectedMaterials.length}个物料，开始打包下载...`)
  // 这里应该是实际的下载逻辑
  // 模拟下载完成
  setTimeout(() => {
    ElMessage.success('下载完成')
  }, 1000)
}

// 关闭下载物料内容弹窗
function handleCloseDownloadMaterial() {
  downloadMaterialVisible.value = false
}

// 关联合同
function handleLinkContract(row) {
  // 保存选中的需求数据和类型
  selectedRequirementData.value = { ...row }
  selectedRequirementType.value = row.dtype
  // 打开关联合同弹窗
  relateContractVisible.value = true
}
function handleCloseRelateContract() {
  relateContractVisible.value = false

}

// 处理关联合同提交
function handleRelateContractSubmit(formData) {
  relevanceContract({
    contractId: Number(formData.contractId),
    demandId: Number(formData.id),
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success('关联合同成功')
      getRequirementList()
      handleCloseRelateContract()
      router.push({
        path: `/business/contract/Requirement/createRequirement/${res.data}`
      })
    }
  }).catch(() => {
    getRequirementList()
    handleCloseRelateContract()
  })
  // 这里应该是实际的关联合同逻辑
}

// 删除需求
function handleDelete(row) {
  ElMessageBox.confirm('确定要删除该需求吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 在实际项目中这里会调用删除接口
      removeDemand(row.id).then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          getRequirementList()
        }
      })
    })
    .catch(() => {})
}

// 分页大小改变
function handleSizeChange(val) {
  query.pageSize = val
  query.pageNum = 1
  getRequirementList()
}

// 当前页码改变
function handleCurrentChange(val) {
  query.pageNum = val
  getRequirementList()
}

</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header-bar {
  margin-bottom: 10px;
}

.header-with-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-form {
  margin-top: 20px;
}
</style>
